package bpm.util;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;

/**
 * 
 * @author ZhaoWangLong Oct 26, 2011
 *
 */
public class HttpRequestUtil {
	public static InputStream getStream(String[] param, String[] values, String urlAddress){
		URL url = null;
		HttpURLConnection conn = null;
		OutputStream os = null;
		try {
			url=new URL(urlAddress);
			conn=(HttpURLConnection)url.openConnection();
			conn.setReadTimeout(3*1000);
			conn.setDoOutput(true);
			conn.setDoInput(true);
			conn.setUseCaches(false);
			conn.setRequestMethod("POST");
			conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
			os = conn.getOutputStream();
			
			StringBuffer body=null;
			if(param!=null){
				body=new StringBuffer();
				for (int i = 0; i < param.length; i++) {
					if(i!=param.length-1){
						body.append(param[i]).append("=").append(URLEncoder.encode(values[i],"UTF-8"))
						.append("&");
					}else{
						body.append(param[i]).append("=").append(URLEncoder.encode(values[i],"UTF-8"));
					}
				}
			}
			if(body!=null){
				os.write(body.toString().getBytes());
				InputStream is = conn.getInputStream();
				return is;
			}else{
				return null;
			}
		} catch (Exception e) {
			e.printStackTrace();
			throw new RuntimeException(e);
		}
	}
	
	public static void main(String[] args) throws IOException {
		String[] param=new String[]{"domainID","startDate","isAll"};
		String[] values=new String[]{"001","2011-10-20 00:00:00","0"};
		InputStream is=getStream(param,values,"http://10.1.66.231:8081/syn/sync/list.jsp");
		byte[] buff = new byte[10 * 1024];
		int readLength = 0;
		while((readLength = is.read(buff)) != -1){
			System.out.print(new String(buff, 0, readLength, "GBK"));
		}
		//System.out.println(str);
	}
}
